Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list.
Analyze and describe its complexity.
题目大意:合并k个排序好的链表,分析复杂度
题目难度:Hard
import java.util.*;
/**
* Created by gzdaijie on 16/5/9
* 优先队列,相当于最小堆,每次取出最小值,如果有后续节点,入队
* 复杂度O(N*K*log(K)) => N个数,维护K大小的优先队列(因为每次出队,至多入队一个)
*/
public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
Queue<ListNode> queue = new PriorityQueue<ListNode>(10, new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
if (o1.val > o2.val) return 1;
if (o1.val < o2.val) return -1;
return 0;
}
});
for (int i = 0; i < lists.length; i++) {
if (lists[i] != null) queue.add(lists[i]);
}
ListNode head = new ListNode(0);
ListNode p = head;
while (!queue.isEmpty()) {
p.next = queue.poll();
p = p.next;
if (p.next != null) {
queue.add(p.next);
}
p.next = null;
}
return head.next;
}
}